import React,{useEffect, useRef, useState,forwardRef,useImperativeHandle} from "react";
import {Tabs,Form,Select,Button,notification,Cascader,Modal,message,Spin} from 'antd'
import LlxForm from 'components/LlxForm/index'
import classNames from "classnames";
import { connect } from 'react-redux'
import {setPageData,addHistoryRouter,setDictionaries} from 'redux/action'
import LlxTable from 'components/LlxTable'
import {getExploreDataRule,delExploreDataRule,editRulesBatch,pushExploreDataRule} from 'api/index'

import {FormOutlined,UpCircleOutlined,DownCircleOutlined} from '@ant-design/icons'

const {TabPane} = Tabs

const options = [
  { id: 410, poolName: '教学区', children: [{ id: 411, poolName: '精读书' }, { id: 412, poolName: '学习视频' }] },
  { id: 510, poolName: '泛读区', children: [{ id: 511, poolName: '泛读书' }, { id: 512, poolName: '视频' }] }
]

// 新增弹框
const AreaRuleDialog = forwardRef((props, ref) => {
  const {isModalVisible, setIsModalVisible,dictionaries,userName,tabIndex,sort} = props

  const [formNew] = Form.useForm();//新增单词

  const [refresh, setRefresh] = useState(false);

  useEffect(() => {
  refresh && setTimeout(() => setRefresh(false))
  }, [refresh])


  useImperativeHandle(ref, () => ({
    formNew
  }));



  useEffect(()=>{
    if(!isModalVisible) return
    setRefresh(true)

  },[isModalVisible])// eslint-disable-line react-hooks/exhaustive-deps

  const loading = useRef(false)

   // 新增表单
   const newWordItem = [
  {label: '推送模块', name: 'model', span: 20, rules:[
    {
      required: true,
      message: '请选择模块'
    },
  ] ,render:()=>{
    return  <Cascader defaultValue={formNew.getFieldValue().modal}  fieldNames={{value:'id',label:'poolName'}} options={options}  placeholder="请选择模块" />
  }},
  {label: '等级', name: 'gradeId', span: 20 , rules:[
    {
      required: true,
      message: '请选择等级'
    },
  ],render:()=>{
    return   <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择等级'}
    options={dictionaries.LevelExplore}
  >
  </Select>
  }},
  {label: '数量',type:'input', name: 'pushNumber' ,rules:[
    {
      required: true,
      message: '请输入数量'
    },
  ] , span: 20 }
   ]
   
   const handleOk = () => {
    if(loading.current) return
    
    loading.current=true
    formNew.validateFields().then(async()=>{

        const data  = {
          accountType:  dictionaries.AppAcountType[tabIndex-1].id,
          districtId: formNew.getFieldValue().model[0],
          gradeId: formNew.getFieldValue().gradeId,
          id: formNew.getFieldValue().id,
          levelId: formNew.getFieldValue().levelId,
          modelId: formNew.getFieldValue().model[1],
          pushNumber: formNew.getFieldValue().pushNumber,
          sort: formNew.getFieldValue().sort||sort
        }

       await pushExploreDataRule(data)

       if(formNew.getFieldValue().id) {
        notification.success({
          message: '编辑成功',
          description: '操作人：' + userName,
          duration:1.5
        });
       } else {
        notification.success({
          message: '新增成功',
          description: '操作人：' + userName,
          duration:1.5
        });
       }

      
       formNew.resetFields()
       setIsModalVisible(false);

      props.getNewList()
    }).catch(err=>{
       console.log(err);
    }).finally(()=>{
      loading.current=false
    })
   };

  const handleCancel = () => {
    formNew.resetFields()
    setIsModalVisible(false);
  };

  return   <Modal destroyOnClose width={700} title="探索规则配置" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
       <LlxForm form={formNew} preserve={true} labelCol={5} formItem={newWordItem} />
   </Modal>
})


function AreaRule(props) {

const {dictionaries} = props
const userName = props.userInfo.user.userName
const [form] = Form.useForm()
const [loading,setLoading] = useState(false)
const [isModalVisible,setIsModalVisible] = useState(false)
const [tabIndex,setTabIndex] = useState('1')
const rule = useRef()
//初始表格数据
const [dataSource,setDataSource] = useState([])
const columns = [
  {title: '序号',fixed:'left', dataIndex: 'sort',width:60, key: 'sort', align: 'center'},
  {title: '区域', dataIndex: 'districtName',width:100, key: 'districtName', align: 'center'},
  {title: '模块', dataIndex: 'modelName',width:100, key: 'modelName', align: 'center'},
  {title: '等级', dataIndex: 'gradeName',width:150, key: 'gradeName', align: 'center'},
  {title: '数量', dataIndex: 'pushNumber',width:180, key: 'pushNumber', align: 'center'},
  {title: '区域总数', dataIndex: 'poolCount',width:150, key: 'poolCount', align: 'center'},
  {title: '更新人',width:120, dataIndex: 'updateBy', key: 'updateBy', align: 'center',render: (text, record) => {
    return  <div className={classNames(userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
    {text}
 </div>
 }},
  {title: '更新时间', dataIndex: 'updateTime', key: 'updateTime', align: 'center',width:150},
  {title: '操作',fixed:'right', dataIndex: 'operate', key: 'operate', align: 'center',width:120,render:(text,row)=>{
    return  <div>
      <FormOutlined onClick={()=>editRule(row)} style={{fontSize:'20px'}} className="text-link"/>&nbsp;&nbsp;
      <UpCircleOutlined onClick={()=>goTop(row)} style={{fontSize:'20px'}} className="text-link"/>&nbsp;&nbsp;
      <DownCircleOutlined onClick={()=>goBottom(row)} style={{fontSize:'20px'}} className="text-link"/>
   </div>
  }}
]

// 表单数据
const formItem = [
  {label: '级别', name: 'levelId', span: 5,render: () => {
    return <Select
    optionFilterProp="dictValue"
    showSearch
    defaultValue={106}
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择级别'}
    options={dictionaries.Level}
  >
  </Select>
}}
]
//选择数据
const [selectedRowKeys,setselectedRowKeys] = useState([])
const rowSelection  = useRef({
  selectedRowKeys: selectedRowKeys,
  onChange: value => {
  setselectedRowKeys(value)
  rowSelection.current.selectedRowKeys = value
  }
})

// 初始化
//1缓存页面数据 缓存表单数据
useEffect(()=>{
  form.setFieldsValue(props.tabList.filter(i=>i.url==='areaPush/explorePoolRule')[0]?.data?.form)
  },[]) // eslint-disable-line react-hooks/exhaustive-deps

// 1.切换tab
const callback = (key)  => {
    setTabIndex(key)
}
// 1.1
  useEffect(()=>{
    getNewList()
  },[tabIndex]) // eslint-disable-line react-hooks/exhaustive-deps

  // 2.获取数据
  const getNewList =async(value) => {
    setLoading(true)
    // 缓存数据
   const data = {
    form:form.getFieldValue(),
    tab:1
   }
   props.setPageDataFn('areaPush/explorePoolRule',data) 

   const params = {
    levelId: form.getFieldValue().levelId||106,
    pageSize: 100,
    accountType: dictionaries.AppAcountType[tabIndex-1].id
  }
  const res = await getExploreDataRule(params)

  setDataSource(res.result.records)

  setLoading(false)
  }
//  3.新增
const addRule = () => {
  rule.current.formNew.setFieldsValue({
    id:'',
    pushNumber:'',
    sort:dataSource.length+1,
    gradeId:'',
    levelId:form.getFieldValue().levelId||106,
    modal:[],
  })

  setIsModalVisible(true)
}
// 5.编辑
const editRule = (value) => {

  rule.current.formNew.setFieldsValue({
    id:value.id,
    pushNumber:value.pushNumber,
    sort:value.sort,
    gradeId:value.gradeId,
    levelId:value.levelId,
    modal:[value.districtId,value.modelId],
  })

  setIsModalVisible(true)
}
// 6.上移
const goTop = async(value) => {
  
  const index = dataSource.findIndex(i=>i.id===value.id)

  if(index===0){
    message.error('已经是第一个')
    return
  }

  await editRulesBatch([{
    id: value.id,
    sort: value.sort - 1
  }, {
    id: dataSource[index - 1].id,
    sort: dataSource[index - 1].sort + 1
  }])

  getNewList()
}
// 7.下移
const goBottom = async (value) => {
  

  const index = dataSource.findIndex(i=>i.id===value.id)

  if(index===dataSource.length-1) {
    message.error('已经是最后一个了')
    return
  }

  await editRulesBatch([{
    id: value.id,
    sort: value.sort + 1
  }, {
    id: dataSource[index + 1].id,
    sort: dataSource[index + 1].sort - 1
  }])

  getNewList()
}
// 8.移除
const removeRule = async () => { 

  for(let i = 0;i<selectedRowKeys.length;i++){
    await delExploreDataRule(selectedRowKeys[i])
  }

  message.success('删除成功')
  getNewList()
}
     
return  <div  className="app-content animate__animated animate__fadeIn overflow">

    <LlxForm form={form} formItem={formItem}/>

    <div className="operate-btn">
     <div>
           <Button  onClick={addRule} type='primary' className='animate__animated animate__fadeInLeft'>新增规则</Button>
           <Button onClick={removeRule} disabled={!selectedRowKeys.length} danger type='primary' className='animate__animated animate__fadeInLeft'>删除</Button>
       </div>
    </div>

    <Tabs  activeKey={tabIndex} onChange={callback} className="app-content animate__animated animate__fadeIn">
      {
        dictionaries.AppAcountType.map((i,j)=>{
          return  <TabPane tab={i.dictValue} key={j+1}>
          <LlxTable
          loading={loading} 
          paginationHide={true}
          selectedRowShow={true}
          rowSelection={rowSelection.current}
          height={320}
          getNewList={getNewList}
          columns={columns}
          dataSource={dataSource}/>
       </TabPane>
        })
      }
    </Tabs>


    <AreaRuleDialog ref={rule} tabIndex={tabIndex} sort={dataSource.length+1} getNewList={getNewList} isModalVisible={isModalVisible} form={form} userName={userName} dictionaries={dictionaries} setIsModalVisible={setIsModalVisible}></AreaRuleDialog>
</div>
}


// 映射方法
const mapDispatchToProps = (dispatch) => {
  return {
    addRouter: (route) => dispatch(addHistoryRouter(route)),
    setPageDataFn: (url,data) => dispatch(setPageData(url,data)),
    setDictionaries: (url,data) => dispatch(setDictionaries(url,data))
  }
}

export default connect((state)=>{
  return {tabList:state.tabList,examineStatus:state.examineStatus,userInfo:state.userInfo,dictionaries:state.dictionaries}
},mapDispatchToProps)(AreaRule)
